package cn.simonfish.carrier.common;

import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by simon on 2017/9/15.
 */
public class Dict {

    private static final String CONFIG_FILE_NAME = "dict.yml";

    private static Map<String,Object> dictMap = new HashMap();

    static {
        dictMap = loadRoot();
    }

    private static Map loadRoot(){
        InputStream stream = Dict.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
        try {
            if(stream == null){
                throw new RuntimeException(String.format("'%s' is missing.",CONFIG_FILE_NAME));
            }
            Yaml yml = new Yaml();
            return yml.loadAs(stream, Map.class);
        }finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static Object get(String key){
        return dictMap.get(key);
    }

    /**
     * 通过字段和值,过滤出一个Map出来
     * @param key
     * @param field
     * @param val
     * @return
     */
    public static Map getByFilter(String key,String field,Object val){
        List<Map> list = (List<Map>) dictMap.get(key);
        for (Map map: list  ) {
            if(val.equals(map.get(field))){
                Map copy = new HashMap();
                copy.putAll(map);
                return copy;
            }
        }
        return null;
    }

}
